package your.packag;


import java.io.IOException;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;

import DAO.MyData;
import DTO.ExpendDTO;
import DTO.IncomeDTO;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.ZoomButtonsController.OnZoomListener;

public class CreateExpendActivity extends Activity implements OnItemSelectedListener,OnClickListener{
	
	Spinner accSpinner;
	Spinner categorySpinner;
	Spinner curSpinner;
	
	EditText money;
	EditText title;
	EditText date;
	
	Button create;
	EditText description;
	
	private int mYear;
	private int mMonth;
	private int mDay;
	Dialog datePicker;

	ExpendDTO expendDTO;
	DefaultHttpClient postClient;
	String valueacc,valuecate,valuecur;
	List<Cookie> cookies;
	ProgressDialog dialog;
	 private Handler handler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	        	dialog.dismiss();
	        	LoadUI();
	        	

	        }
		};
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_expend);
        
        postClient = LoginActivity.postClient;
        
        

        dialog = new ProgressDialog(this);
        dialog = ProgressDialog.show(this, "", 
                "Loading. Please wait...", true);
        new Thread(new Runnable() {
			
			  
				  public void run() {
					  LoadData();
					  handler.sendEmptyMessage(0);
				  }}).start();
	
        
       
		
		
        
	}
	public void LoadUI()
	{
		accSpinner = (Spinner)findViewById(R.id.createexpendspinner2);
        categorySpinner = (Spinner)findViewById(R.id.createexpendspinner1);
        curSpinner = (Spinner)findViewById(R.id.createexpendspinner3);
        
        money = (EditText)findViewById(R.id.createexpendeditText1);
        title = (EditText)findViewById(R.id.createexpendeditText2);
        date = (EditText)findViewById(R.id.createexpendeditText3);
        description = (EditText)findViewById(R.id.createexpendeditText4);
        
        create = (Button)findViewById(R.id.createexpendbutton1);
        ArrayAdapter<String> account = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, expendDTO.account());
		account.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		accSpinner.setAdapter(account);
		
		ArrayAdapter<String> category = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, expendDTO.category());
		account.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		categorySpinner.setAdapter(category);
		

		ArrayAdapter<String> currency = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_item, expendDTO.currency());
		account.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		curSpinner.setAdapter(currency);
		
		create.setOnClickListener(this);
		date.setOnClickListener(this);

		accSpinner.setOnItemSelectedListener(this);
		categorySpinner.setOnItemSelectedListener(this);
		curSpinner.setOnItemSelectedListener(this);
	}
	public void LoadData() 
	{
		
        
        String xml;
		try {
			/*HttpGet httpGet = new HttpGet("http://smartwebvina.com/smartlive/index.php?option=com_mymonney");
	        HttpResponse response = LoginActivity.postClient.execute(httpGet);
	        HttpEntity httpEntity =response.getEntity();
			xml = EntityUtils.toString(httpEntity);
			org.jsoup.nodes.Document doc = Jsoup.parse(xml);*/
			MyData data = new MyData();
		    expendDTO = data.readExpend(FinancialActivity.doc);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		//}
		
		
	
	}
	public List<Cookie> CreateExpend(String url,String acc,String cate,String money,String title,String curr,String date,String des) {

		   // Setup a HTTP client, HttpPost (that contains data you wanna send) and
		   // a HttpResponse that gonna catch a response.
		 //  postClient = new DefaultHttpClient();
		   HttpPost httpPost = new HttpPost(url);
		   HttpResponse response;
		   List<Cookie> cookies = null;
		  
		

		   try {   
			  
		      // Make a List. Increase the size as you wish.
		      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		      // Add your form name and a text that belongs to the actual form.
		      
		     
		      nameValuePairs.add(new BasicNameValuePair("cat", cate));
		      nameValuePairs.add(new BasicNameValuePair("acc",acc));
		      nameValuePairs.add(new BasicNameValuePair("money",money));
		      nameValuePairs.add(new BasicNameValuePair("currency",curr));
		      nameValuePairs.add(new BasicNameValuePair("name_i_u",title));
		      nameValuePairs.add(new BasicNameValuePair("date",date));
		      nameValuePairs.add(new BasicNameValuePair("description",des));
		
		    //  nameValuePairs.add(new BasicNameValuePair("remember", "yes"));
		      

		      nameValuePairs.add(new BasicNameValuePair("option", "com_mymonney"));  
		      nameValuePairs.add(new BasicNameValuePair("type_i_u", "0"));
		      nameValuePairs.add(new BasicNameValuePair("task", "createio"));
		      nameValuePairs.add(new BasicNameValuePair("view", "parents"));
		     nameValuePairs.add(new BasicNameValuePair("f6f6cb580925b9a2a5f5d2e83482456e", "1"));

		      // Set the entity of your HttpPost.
		      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

		      // Execute your request against the given url and catch the response.
		      response = postClient.execute(httpPost);
		    
	
		      // Status code 200 == successfully posted data.
		      if(response.getStatusLine().getStatusCode() == 200) {
		         // Green light. Catch your cookies from your HTTP response.
		          cookies =  postClient.getCookieStore().getCookies(); 
		         return  cookies;
		      }
		   } catch (Exception e) {
		   }
		   return  cookies;
	
	}
	public void onItemSelected(AdapterView<?> parent, View view, int pos,
			long id) {
		
		
	}
	public void onNothingSelected(AdapterView<?> arg0) {
		
	}
	public void onClick(View v) {
		switch(v.getId())
		{
		
		case R.id.createexpendbutton1:
			getValueSpinner();
			cookies = CreateExpend("http://smartwebvina.com/smartlive/index.php?option=com_mymonney",
					valueacc,
					valuecate,
					money.getText().toString(),
					title.getText().toString(),
					valuecur,
					date.getText().toString(),
					description.getText().toString());
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Create Sucess")
		       .setCancelable(false)
		       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		               dialog.cancel();
		           }
		       });
			AlertDialog alert = builder.create();
			alert.show();
		
			break;
		case R.id.createincomeeditText3:
			final Calendar c = Calendar.getInstance();
			mYear = c.get(Calendar.YEAR);
			mMonth = c.get(Calendar.MONTH);
			mDay = c.get(Calendar.DAY_OF_MONTH);
			datePicker = new DatePickerDialog(this, mDateSetListener, mYear,
					mMonth, mDay);
			datePicker.show();
			break;
		}

	}

	private void updateDisplay() {
		String month = String.valueOf(mMonth);
		if(mMonth<10)
		{
			month = "0"+month;
		}
		String day = String.valueOf(mDay);
		if(mDay<10)
		{
			day = "0"+day;
		}
		date.setText(new StringBuilder()
				// Month is 0 based, just add 1
				.append(mYear).append("-").append(month).append("-")
				.append(day));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear+1;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	
	public void getValueSpinner()
	{
		String temp = accSpinner.getSelectedItem().toString();
		for(int i =0 ;i< expendDTO.account().size(); i++)
		{
			if(temp.compareTo(expendDTO.account().get(i))==0)
			{
				valueacc = expendDTO.valueacc().get(i);
			}
		}
		
		temp = categorySpinner.getSelectedItem().toString();
		
		for(int i =0 ;i< expendDTO.category().size(); i++)
		{
			if(temp.compareTo(expendDTO.category().get(i))==0)
			{
				valuecate = expendDTO.valuecate().get(i);
			}
		}
		
		
		temp = curSpinner.getSelectedItem().toString();
		
		for(int i =0 ;i< expendDTO.currency().size(); i++)
		{
			if(temp.compareTo(expendDTO.currency().get(i))==0)
			{
				valuecur = expendDTO.valuecur().get(i);
			}
		}
		
		
		
	}
	

}
